<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  

  
  <title>二叉堆，优先队列 | My Blog</title>
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <meta name="description" content="以下内容部分摘自数据结构篇——优先级队列（堆）。 堆，或称二叉堆、优先队列，本质上是一种完全二叉树，分为：  最小堆（小根堆）：树中每个非叶子结点都不大于其左右孩子结点的值，也就是根节点最小的堆。 最大堆（大根堆）：树中每个非叶子结点都不小于其左右孩子结点的值，也就是根节点最大的堆。  存储方式堆本质上是一颗完全二叉树，使用数组进行存储，从a[1]开始存储，这样对于下标为k的结点a[k]来说，其左">
<meta property="og:type" content="article">
<meta property="og:title" content="二叉堆，优先队列">
<meta property="og:url" content="http://yoursite.com/heap/index.html">
<meta property="og:site_name" content="My Blog">
<meta property="og:description" content="以下内容部分摘自数据结构篇——优先级队列（堆）。 堆，或称二叉堆、优先队列，本质上是一种完全二叉树，分为：  最小堆（小根堆）：树中每个非叶子结点都不大于其左右孩子结点的值，也就是根节点最小的堆。 最大堆（大根堆）：树中每个非叶子结点都不小于其左右孩子结点的值，也就是根节点最大的堆。  存储方式堆本质上是一颗完全二叉树，使用数组进行存储，从a[1]开始存储，这样对于下标为k的结点a[k]来说，其左">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2020-05-10T15:33:50.000Z">
<meta property="article:modified_time" content="2020-10-30T14:40:34.917Z">
<meta property="article:author" content="Alanisia">
<meta property="article:tag" content="data structure">
<meta name="twitter:card" content="summary">
  
    <link rel="alternate" href="/atom.xml" title="My Blog" type="application/atom+xml">
  
  
    <link rel="icon" href="/favicon.ico">
  
  
    <link href="//fonts.googleapis.com/css?family=Source+Code+Pro" rel="stylesheet" type="text/css">
  
  
<link rel="stylesheet" href="/css/style.css">

<meta name="generator" content="Hexo 4.2.0"></head>

<body>
  <div id="container">
    <div id="wrap">
      <header id="header">
  <div id="banner"></div>
  <div id="header-outer" class="outer">
    <div id="header-title" class="inner">
      <h1 id="logo-wrap">
        <a href="/" id="logo">My Blog</a>
      </h1>
      
        <h2 id="subtitle-wrap">
          <a href="/" id="subtitle">我的博客 -- 记录编程过程中所遇到的问题与总结</a>
        </h2>
      
    </div>
    <div id="header-inner" class="inner">
      <nav id="main-nav">
        <a id="main-nav-toggle" class="nav-icon"></a>
        
          <a class="main-nav-link" href="/">Home</a>
        
          <a class="main-nav-link" href="/archives">Archives</a>
        
      </nav>
      <nav id="sub-nav">
        
          <a id="nav-rss-link" class="nav-icon" href="/atom.xml" title="RSS Feed"></a>
        
        <a id="nav-search-btn" class="nav-icon" title="搜索"></a>
      </nav>
      <div id="search-form-wrap">
        <form action="//google.com/search" method="get" accept-charset="UTF-8" class="search-form"><input type="search" name="q" class="search-form-input" placeholder="Search"><button type="submit" class="search-form-submit">&#xF002;</button><input type="hidden" name="sitesearch" value="http://yoursite.com"></form>
      </div>
    </div>
  </div>
</header>
      <div class="outer">
        <section id="main"><article id="post-heap" class="article article-type-post" itemscope itemprop="blogPost">
  <div class="article-meta">
    <a href="/heap/" class="article-date">
  <time datetime="2020-05-10T15:33:50.000Z" itemprop="datePublished">2020-05-10</time>
</a>
    
  </div>
  <div class="article-inner">
    
    
      <header class="article-header">
        
  
    <h1 class="article-title" itemprop="name">
      二叉堆，优先队列
    </h1>
  

      </header>
    
    <div class="article-entry" itemprop="articleBody">
      
        <p>以下内容部分摘自<a href="https://www.cnblogs.com/czc1999/p/11823460.html" target="_blank" rel="noopener">数据结构篇——优先级队列（堆）</a>。</p>
<p>堆，或称二叉堆、优先队列，本质上是一种完全二叉树，分为：</p>
<ul>
<li><strong>最小堆（小根堆）</strong>：树中每个非叶子结点都不大于其左右孩子结点的值，也就是根节点最小的堆。</li>
<li><strong>最大堆（大根堆）</strong>：树中每个非叶子结点都不小于其左右孩子结点的值，也就是根节点最大的堆。</li>
</ul>
<h2 id="存储方式"><a href="#存储方式" class="headerlink" title="存储方式"></a>存储方式</h2><p>堆本质上是一颗完全二叉树，使用数组进行存储，从a[1]开始存储，这样对于下标为k的结点a[k]来说，其左孩子的下标为2∗k，右孩子的下标为2∗k+1，且不论 k 是奇数还是偶数，其父亲结点（如果有的话）就是 ⌊k/2⌋。</p>
<h2 id="向上调整"><a href="#向上调整" class="headerlink" title="向上调整"></a>向上调整</h2><p>入队：向一个堆中插入一个元素，并使其仍然保持堆的结构，代码如下：</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">heapinsert</span><span class="params">(<span class="keyword">int</span>* arr, <span class="keyword">int</span> n)</span> </span>&#123;</span><br><span class="line">	<span class="keyword">int</span> k = n;</span><br><span class="line">	<span class="comment">// 如果 K 结点有父节点，且比父节点的权值大</span></span><br><span class="line">	<span class="keyword">while</span> (k &gt; <span class="number">1</span> &amp;&amp; arr[k] &gt; arr[k / <span class="number">2</span>]) &#123;</span><br><span class="line">		<span class="comment">// 交换 K 与父节点的值</span></span><br><span class="line">		swap(arr[k / <span class="number">2</span>], arr[k]);</span><br><span class="line">		k &gt;&gt;= <span class="number">1</span>;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// 添加元素</span></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">insert</span><span class="params">(<span class="keyword">int</span>* arr, <span class="keyword">int</span> n, <span class="keyword">int</span> x)</span> </span>&#123;</span><br><span class="line">	arr[++n] = x;<span class="comment">// 将x置于数组末尾</span></span><br><span class="line">	heapinsert(arr, n);<span class="comment">// 向上调整x</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>时间复杂度为O(log n)。</p>
<h2 id="向下调整"><a href="#向下调整" class="headerlink" title="向下调整"></a>向下调整</h2><p>出队：删除一个堆中的堆顶元素，并使其仍然保持堆的结构，代码如下：</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">heapify</span><span class="params">(<span class="keyword">int</span>* arr, <span class="keyword">int</span> k, <span class="keyword">int</span> n)</span> </span>&#123;</span><br><span class="line">	<span class="comment">// 如果结点 K 存在左孩子</span></span><br><span class="line">	<span class="keyword">while</span> (k * <span class="number">2</span> &lt;= n) &#123;</span><br><span class="line">		<span class="keyword">int</span> left = k * <span class="number">2</span>;</span><br><span class="line">		<span class="comment">// 如果存在右孩子，并且右孩子的权值大于左孩子</span></span><br><span class="line">		<span class="keyword">if</span> (left + <span class="number">1</span> &lt;= n &amp;&amp; arr[left] &lt; arr[left + <span class="number">1</span>])</span><br><span class="line">			left++; <span class="comment">// 就选中右孩子</span></span><br><span class="line">		<span class="comment">// 如果节点 K 的权值已经大于左右孩子中较大的节点</span></span><br><span class="line">		<span class="keyword">if</span> (arr[k] &gt; arr[left])</span><br><span class="line">			<span class="keyword">break</span>;</span><br><span class="line">		swap(arr[left], arr[k]);</span><br><span class="line">		k = left;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// 删除堆顶</span></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">deleteTop</span><span class="params">(<span class="keyword">int</span>* arr, <span class="keyword">int</span> n)</span> </span>&#123;</span><br><span class="line">	arr[<span class="number">1</span>] = arr[n--];<span class="comment">// 用最后一个元素覆盖第一个元素，并让n-1</span></span><br><span class="line">	heapify(arr, <span class="number">1</span>, n);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>时间复杂度为O(log n)。</p>
<h2 id="建堆"><a href="#建堆" class="headerlink" title="建堆"></a>建堆</h2><h3 id="自顶向下建堆"><a href="#自顶向下建堆" class="headerlink" title="自顶向下建堆"></a>自顶向下建堆</h3><p>自顶向下建堆的思想是，从第 i=1 个元素开始，对其进行向上调整，始终使前 i 个元素保持堆的结构。时间复杂度 O(n log n)。</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">ArrayToHeap</span><span class="params">(<span class="keyword">int</span> *a,<span class="keyword">int</span> n)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">1</span>; i &lt;= n; i++) &#123;</span><br><span class="line">        heapinsert(a, i);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="自底向上建堆"><a href="#自底向上建堆" class="headerlink" title="自底向上建堆"></a>自底向上建堆</h3><p>自底向上建堆的思想是，从底 i=⌊n/2⌋ 个元素开始，对其进行向下调整，始终让后 n−i 个元素保持堆的结构。</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">ArrayToBheap</span><span class="params">(<span class="keyword">int</span> *a, <span class="keyword">int</span> n)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">int</span> i = n / <span class="number">2</span>;</span><br><span class="line">    <span class="keyword">for</span> (; i &gt;= <span class="number">1</span>; i--) &#123;</span><br><span class="line">        heapify(a, i, n);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="堆排序"><a href="#堆排序" class="headerlink" title="堆排序"></a>堆排序</h2><p>堆排序的思想：假设一个大根堆有 n 个元素，每次把第 1 个元素，与第 n 个元素交换，对第一个元素进行向下调整，并使得 n=n−1 ，直到 n=1：</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">heapSort</span><span class="params">(<span class="keyword">int</span>* arr, <span class="keyword">int</span> n)</span> </span>&#123;</span><br><span class="line">	<span class="comment">// 先自底向上建堆</span></span><br><span class="line">	<span class="keyword">int</span> i = n / <span class="number">2</span>;</span><br><span class="line">	<span class="keyword">for</span> (; i &gt;= <span class="number">1</span>; i--) &#123;</span><br><span class="line">		heapify(arr, i, n);</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">for</span> (<span class="keyword">int</span> i = n; i &gt; <span class="number">1</span>; i--) &#123;</span><br><span class="line">		swap(arr[<span class="number">1</span>], arr[i]);</span><br><span class="line">		heapify(arr, <span class="number">1</span>, i - <span class="number">1</span>);</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
      
    </div>
    <footer class="article-footer">
      <a data-url="http://yoursite.com/heap/" data-id="ckpb8zvjo000mdsvl80ryg2au" class="article-share-link">Share</a>
      
      
  <ul class="article-tag-list" itemprop="keywords"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/data-structure/" rel="tag">data structure</a></li></ul>

    </footer>
  </div>
  
    
<nav id="article-nav">
  
    <a href="/bubblesort/" id="article-nav-newer" class="article-nav-link-wrap">
      <strong class="article-nav-caption">Newer</strong>
      <div class="article-nav-title">
        
          冒泡排序
        
      </div>
    </a>
  
  
    <a href="/radixsort/" id="article-nav-older" class="article-nav-link-wrap">
      <strong class="article-nav-caption">Older</strong>
      <div class="article-nav-title">基数排序</div>
    </a>
  
</nav>

  
</article>

</section>
        
          <aside id="sidebar">
  
    

  
    
  <div class="widget-wrap">
    <h3 class="widget-title">标签</h3>
    <div class="widget">
      <ul class="tag-list" itemprop="keywords"><li class="tag-list-item"><a class="tag-list-link" href="/tags/android/" rel="tag">android</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/data-structure/" rel="tag">data structure</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/docker/" rel="tag">docker</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/git/" rel="tag">git</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/go/" rel="tag">go</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/hexo/" rel="tag">hexo</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/java/" rel="tag">java</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/javascript/" rel="tag">javascript</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/json/" rel="tag">json</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/linux/" rel="tag">linux</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/maven/" rel="tag">maven</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/mybatis/" rel="tag">mybatis</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/mysql/" rel="tag">mysql</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/network/" rel="tag">network</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/nginx/" rel="tag">nginx</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/nodejs/" rel="tag">nodejs</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/searching/" rel="tag">searching</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/sorting/" rel="tag">sorting</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/sublime-text/" rel="tag">sublime text</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/termux/" rel="tag">termux</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/theia/" rel="tag">theia</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/typora/" rel="tag">typora</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/vala/" rel="tag">vala</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/vim/" rel="tag">vim</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/vue/" rel="tag">vue</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/zig/" rel="tag">zig</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/zookeeper/" rel="tag">zookeeper</a></li></ul>
    </div>
  </div>


  
    
  <div class="widget-wrap">
    <h3 class="widget-title">标签云</h3>
    <div class="widget tagcloud">
      <a href="/tags/android/" style="font-size: 10px;">android</a> <a href="/tags/data-structure/" style="font-size: 10px;">data structure</a> <a href="/tags/docker/" style="font-size: 10px;">docker</a> <a href="/tags/git/" style="font-size: 15px;">git</a> <a href="/tags/go/" style="font-size: 10px;">go</a> <a href="/tags/hexo/" style="font-size: 10px;">hexo</a> <a href="/tags/java/" style="font-size: 18.33px;">java</a> <a href="/tags/javascript/" style="font-size: 11.67px;">javascript</a> <a href="/tags/json/" style="font-size: 10px;">json</a> <a href="/tags/linux/" style="font-size: 20px;">linux</a> <a href="/tags/maven/" style="font-size: 10px;">maven</a> <a href="/tags/mybatis/" style="font-size: 10px;">mybatis</a> <a href="/tags/mysql/" style="font-size: 11.67px;">mysql</a> <a href="/tags/network/" style="font-size: 11.67px;">network</a> <a href="/tags/nginx/" style="font-size: 10px;">nginx</a> <a href="/tags/nodejs/" style="font-size: 13.33px;">nodejs</a> <a href="/tags/searching/" style="font-size: 10px;">searching</a> <a href="/tags/sorting/" style="font-size: 16.67px;">sorting</a> <a href="/tags/sublime-text/" style="font-size: 10px;">sublime text</a> <a href="/tags/termux/" style="font-size: 10px;">termux</a> <a href="/tags/theia/" style="font-size: 10px;">theia</a> <a href="/tags/typora/" style="font-size: 10px;">typora</a> <a href="/tags/vala/" style="font-size: 10px;">vala</a> <a href="/tags/vim/" style="font-size: 15px;">vim</a> <a href="/tags/vue/" style="font-size: 11.67px;">vue</a> <a href="/tags/zig/" style="font-size: 10px;">zig</a> <a href="/tags/zookeeper/" style="font-size: 10px;">zookeeper</a>
    </div>
  </div>

  
    
  <div class="widget-wrap">
    <h3 class="widget-title">归档</h3>
    <div class="widget">
      <ul class="archive-list"><li class="archive-list-item"><a class="archive-list-link" href="/archives/2021/05/">五月 2021</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2021/04/">四月 2021</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2021/03/">三月 2021</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2021/01/">一月 2021</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2020/11/">十一月 2020</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2020/10/">十月 2020</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2020/09/">九月 2020</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2020/08/">八月 2020</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2020/07/">七月 2020</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2020/06/">六月 2020</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2020/05/">五月 2020</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2020/03/">三月 2020</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2020/02/">二月 2020</a></li></ul>
    </div>
  </div>


  
    
  <div class="widget-wrap">
    <h3 class="widget-title">最新文章</h3>
    <div class="widget">
      <ul>
        
          <li>
            <a href="/java-hashmap/">java.util.HashMap</a>
          </li>
        
          <li>
            <a href="/jvm/">JVM</a>
          </li>
        
          <li>
            <a href="/java-locks/">Java锁</a>
          </li>
        
          <li>
            <a href="/java-references/">Java引用</a>
          </li>
        
          <li>
            <a href="/gitea/">Gitea</a>
          </li>
        
      </ul>
    </div>
  </div>

  
</aside>
        
      </div>
      <footer id="footer">
  
  <div class="outer">
    <div id="footer-info" class="inner">
      &copy; 2021 Alanisia<br>
      Powered by <a href="http://hexo.io/" target="_blank">Hexo</a>
    </div>
  </div>
</footer>
    </div>
    <nav id="mobile-nav">
  
    <a href="/" class="mobile-nav-link">Home</a>
  
    <a href="/archives" class="mobile-nav-link">Archives</a>
  
</nav>
    

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>


  
<link rel="stylesheet" href="/fancybox/jquery.fancybox.css">

  
<script src="/fancybox/jquery.fancybox.pack.js"></script>




<script src="/js/script.js"></script>




  </div>
</body>
</html>